package cn.zj.util;


import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.File;
import java.io.IOException;
import java.util.Date;


public class ImagesUtil {
    public static void testImageComparison(String expectedFilePath,String actualFilePath) throws IOException,InterruptedException{
        File expectedFile = new File(expectedFilePath);
        File actualFile = new File(actualFilePath);

        //对比两个图片
        BufferedImage bufileInput = ImageIO.read(expectedFile);
        DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
        int sizefileInput = dafileInput.getSize();

        BufferedImage bufileOutput = ImageIO.read(actualFile);
        DataBuffer dafileOutput = bufileOutput.getData().getDataBuffer();
        int sizefileOutput = dafileOutput.getSize();

        Boolean matchFlag = true;
        if(sizefileInput == sizefileOutput){
            for(int j = 0; j <sizefileInput;j++){
                if(dafileInput.getElem(j) != dafileOutput.getElem(j)){
                    matchFlag = false;
                    break;
                }
            }
        }
        else
            matchFlag = false;
        Assert.assertTrue(matchFlag,"测试过程中的截图和期望的截图不一致");
    }

    //截屏，并按当前时间取名保存
    public static void SreenShot(WebDriver driver) throws IOException, InterruptedException {
        try {
            Date date = new Date();
            String picDir = "c:\\dir\\kradarImageLog"+String.valueOf(DateUtil.getYear(date))+"-"+String.valueOf(DateUtil.getMonth(date)+"-"+String.valueOf(DateUtil.getDay(date)));
            if(!new File(picDir).exists()){
                FileUtil.createDir(picDir);
            }
            String filePath = picDir +"\\"+String.valueOf(DateUtil.getHour(new Date()))+"-"+String.valueOf(DateUtil.getMinute(new Date())+"-"+String.valueOf(DateUtil.getSecond(new Date()))+".png");

            File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(srcFile,new File(filePath));


//            File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//            Thread.sleep(3000);
//            FileUtils.copyFile(screenshot,new File(savaFilePath));
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
